/**
 * 准备函数
 */
var operateRight = new Object();
var cCaseDetailEditor;
var mCaseDetailEditor;
$(document).ready(function() {
	
	// 加载权限
	loadRight();
	
	// 加载表格
	queryCase();
	
	// 绑定函数
	$("#queryCaseButton").bind("click", confirmQueryCase);
	$("#createCaseButton").bind("click", showCreateCaseDialog);
	$("#confirmCreateCaseButton").bind("click", confirmCreateCase);
	$("#confirmModifyCaseButton").bind("click", confirmModifyCase);
});

/**
 * 加载权限
 */
function loadRight() {
	operateRight.modifyRight = $("#modify").val();
	operateRight.deleteRight = $("#delete").val();
	operateRight.publishRight = $("#publish").val();
}

/**
 * 查询
 */
function queryCase(pageIndex, pageSize) {
	// 组装参数
	var data = {};
	var title = $('#title').val();
	if (Utils.isNotNull(title)) {
		data['title'] = title;
	}
	
	var isPush = $('#isPush').val();
	if (Utils.isNotNull(isPush)) {
		data['isPush'] = isPush;
	}
	
	// 设置分页参数
	setPageIndex(data, pageIndex, pageSize);
	
	// 调用接口 
	var response = callInterface("post", "home/queryCase", data, false);
	if (response.code == 0) {
		var count = 0;
		if( Utils.isNotNull(response.data) && Utils.isNotNull(response.data.totalCount) ){
			count = response.data.totalCount;
		}
		
		// 清空表格及分页
		$("#dataTable tr:not(:first)").remove();
		$("#pageDiv").html("");

		// 动态添加一行
		if (count == 0) {
			var cols = $("#dataTable").find("tr:first th");
			$('#dataTable').append("<tr><td colspan='" + cols.length + "'>无数据!</td></tr>");
			return false;
		}

		var list = response.data.list;
		if (list != null && list.length > 0) {
			var num =0;
			for ( var i in list) {
				var trHtml = "<tr>";
				trHtml += "<td align='center'>" + list[i].sort + "</td>";
				trHtml += "<td>" + cutString(list[i].title, 50) + "</td>";
				trHtml += "<td>" + cutString(list[i].subTitle, 30) + "</td>";
				// trHtml += "<td>" + cutString(list[i].abstractContent, 50) + "</td>";
				var pushText = list[i].isPush?'是':'否';
				trHtml += "<td align='center'>" + pushText + "</td>";
				trHtml += "<td align='center'>" + list[i].createdTime + "</td>";
				trHtml += "<td align='center'>";
				// 操作
				if (operateRight.modifyRight == 1) {
					trHtml += '<a href="javascript:void(0);" class="edit" onclick="showModifyCaseDialog(\''
						+ list[i].id
						+ '\');">编辑</a> ';
				}
				if (operateRight.deleteRight == 1) {
					trHtml += '<a href="javascript:void(0);" class="delete" onclick="deleteCase(\''
							+ list[i].id
							+ '\');">删除</a> ';
				}
				if (operateRight.publishRight == 1 && !list[i].isPush) {
					trHtml += '<a href="javascript:void(0);" class="copy" onclick="publishCase(\''
							+ list[i].id
							+ '\');">发布</a>';
				} 
				trHtml += "</td>";
				trHtml += "</tr>";

				// 动态添加一行
				$('#dataTable').append(trHtml);
			}
		}
		
		// 调用分页
		layui.use(['laypage'], function() {
			var laypage = layui.laypage;
			laypage.render({
				elem : 'pageDiv',
				// pages : pages,
				curr : pageIndex || 1, // 当前页
				count : count,
				limit : pageSize, 
				skip : true, // 是否开启跳页
				layout : ['count', 'prev', 'page', 'next', 'limit', 'skip'],
				groups : 5, // 连续显示分页数
				jump : function(obj, first) {  
					if (!first) {
						queryCase(obj.curr, obj.limit);
					}
				}
			});
		});
	}
}

/**
 * 确认查询
 */
function confirmQueryCase() {
	queryCase();
}

/**
 * 设置是否隐藏
 */
function publishCase($id) {
	// 获取参数
	var data = {};
	data['id'] = $id;
	data['isPush'] = 1;

	// 调用接口
	var response = callInterface("post", "home/modifyCasePush", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');
		
		// 刷新
		queryCase(currPage);
	}
	else {
		showErrorMsg(response.code, response.message);
	}
	return false;
}

/**
 * 显示创建对话框
 */
function showCreateCaseDialog() {
	$("#createCaseDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#addCaseForm')[0].reset();
	$("#cCaseType").val(" ");
	$("#cCaseImgUrl").val('');
	$("#cCaseImgFileDiv").html('');
	$("#mCaseImgContentUrl").val('');
	$("#mCaseImgContentFileDiv").html('');
	
	$form.render();
	
	//创建editor
	cCaseDetailEditor = undefined;
	var E = window.wangEditor;
    cCaseDetailEditor = new E('#cCaseDetail');
    cCaseDetailEditor.customConfig.customUploadImg = function (files, insert) {
    	//自定义的上传图片到服务器方法 
        uploadEditorImage(files,insert);
    }
    cCaseDetailEditor.create();
    cCaseDetailEditor.txt.clear();
}

/**
 * 确认创建
 */
function confirmCreateCase() {
	// 获取参数
	var data = {};
	var sort = $.trim($('#cCaseSort').val());
	if (sort == '') {
		showAlert('案例排序不能为空!');
		return false;
	}
	data['sort'] = sort;
	
	var title = $.trim($('#cCaseTitle').val());
	if (title == '') {
		showAlert('案例标题不能为空!');
		return false;
	}
	data['title'] = title;

	var subtitle = $.trim($('#cSubtitle').val());
	if (subtitle == '') {
		showAlert('案例标题不能为空!');
		return false;
	}
	data['subTitle'] = subtitle;
	
	var keyWords = $.trim($('#cKeyWords').val());
	if (keyWords != '') {
		data['keyWords'] = keyWords;
	}
	
	var imgUrl = $.trim($('#cCaseImgUrl').val());
	if (imgUrl == '') {
		showAlert('请上传案例图片!');
		return false;
	}
	data['titlePic'] = imgUrl;

	var imgContentUrl = $.trim($('#cCaseImgContentUrl').val());
	if (imgContentUrl == '') {
		showAlert('请上传案例图片!');
		return false;
	}
	data['imgUrl'] = imgContentUrl;
	
	var ehtml = $.trim(cCaseDetailEditor.txt.html());
	if( ehtml == "<p><br></p>" ){
		showAlert('案例详情不能为空!');
		return false;
	}
	data['content'] = ehtml;
	
	data['isPush'] = 0;
	data['pushTime'] = getCurrentDate()

	var seoTitle = $.trim($('#cKeyTitle').val());
	if (seoTitle != '') {
		data['seoTitle']=seoTitle
	}
	var description = $.trim($('#cCaseDesc').val());
	if (description != '') {
		data['description'] = description;
	}

	// 调用接口
	var response = callInterface("post", "home/createCase", data, false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#createCaseDialog').modal("hide");

		// 刷新
		queryCase();
	} else {
		showErrorMsg(response.code, response.message);
	}

	return false;
}

/**
 * 显示修改对话框
 */
function showModifyCaseDialog(id) {
	// 显示对话框
	$("#modifyCaseDialog").modal({
		backdrop : 'static',
		keyboard : false,
		show : true
	});
	$('#modifyCaseForm')[0].reset();
	
	//获取案例详情
	getCaseDetail(id);
}

/**
 * 获取案例详情
 * @param id
 */
function getCaseDetail(id){
	// 调用接口
	var response = callInterface("post", "home/getCaseDetail", {
		'id' : id
	}, false);
	if (response.code == 0) {
		var data = response.data;
		$("#mCaseId").val(data.id);
		$("#mCaseSort").val(data.sort);
		$("#mCaseTitle").val(data.title);
		$("#mSubtitle").val(data.subTitle); //新添加 副标题
		$("#mCaseDesc").val(data.description);
		$("#mKeyWords").val(data.keyWords);
		$("#mKeyTitle").val(data.seoTitle);
		$("#mCaseImgUrl").val(data.titlePic);
		$("#mCaseImgContentUrl").val(data.imgUrl); // 新添加 正文头图
		$("#mCaseImgFileDiv").html(fillFileDiv(data.titlePic));
		$("#mCaseImgContentFileDiv").html(fillFileDiv(data.imgUrl));

		$form.render();
		
		mCaseDetailEditor = undefined;
		var E = window.wangEditor;
	    mCaseDetailEditor = new E('#mCaseDetail');
	    mCaseDetailEditor.customConfig.customUploadImg = function (files, insert) {
	    	uploadEditorImage(files,insert);
	    }
	    mCaseDetailEditor.create();
	    mCaseDetailEditor.txt.html(data.content);
		
	} else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 确认修改
 * @param id
 */
function confirmModifyCase(){
	// 获取参数
	var data = {};
	data['id'] = $.trim($('#mCaseId').val());
	
	var sort = $.trim($('#mCaseSort').val());
	if (sort == '') {
		showAlert('案例排序不能为空!');
		return false;
	}
	data['sort'] = sort;
	
	var title = $.trim($('#mCaseTitle').val());
	if (title == '') {
		showAlert('案例标题不能为空!');
		return false;
	}
	data['title'] = title;

	var subtitle = $.trim($('#mSubtitle').val());
	if (subtitle == '') {
		showAlert('副标题不能为空!');
		return false;
	}
	data['subTitle'] = subtitle;
	
	var description = $.trim($('#mCaseDesc').val());
	if (description != '') {
		data['description'] = description;
	}
	
	var keyWords = $.trim($('#mKeyWords').val());
	if (keyWords != '') {
		data['keyWords'] = keyWords;
	}
	
	var imgUrl = $.trim($('#mCaseImgUrl').val());
	if (imgUrl == '') {
		showAlert('请上传案例图片!');
		return false;
	}
	data['titlePic'] = imgUrl;

	var imgContentUrl = $.trim($('#mCaseImgContentUrl').val());
	if (imgContentUrl == '') {
		showAlert('请上传正文头图图片!');
		return false;
	}
	data['imgUrl'] = imgContentUrl;
	
	var ehtml = $.trim(mCaseDetailEditor.txt.html());
	if( ehtml == "<p><br></p>" ){
		showAlert('案例详情不能为空!');
		return false;
	}
	data['content'] = ehtml;
	
	data['isPush'] = 0;
	data['pushTime'] = getCurrentDate()

	var seoTitle = $.trim($('#mKeyTitle').val());
	if (seoTitle != '') {
		data['seoTitle']=seoTitle
	}
	
	// 调用接口
	var response = callInterface("post", "home/modifyCase", data,
			false);
	if (response.code == 0) {
		showMsg('操作成功!');

		// 关闭对话框
		$('#modifyCaseDialog').modal("hide");

		// 刷新
		queryCase(currPage);
	} else {
		showErrorMsg(response.code, response.message);
	}
}

/**
 * 删除案例
 * @param id
 */
function deleteCase(id){
	// 设置参数
	var data = {
		"id" : id
	};
	
	// 询问框
	layer.confirm('确定删除该案例吗？', {
		offset:'20px',
	  btn: ['确定','取消'] //按钮
	}, function(index){
		// 调用接口
		var response = callInterface("post", "home/deleteCase",
				data, false);
		if (response.code == 0) {
			showMsg('操作成功!');
			
			layer.close(index);
			// 刷新
			queryCase(currPage);
		} else {
			showErrorMsg(response.code, response.message);
		}
	}, function(){
		return;
	});
}


/**
 * 上传图片并预览 
 * $imageUrlFile:图片文件 
 * $imageShowDiv:图片预览 
 * $imageUrlId:图片UrlID
 * $fileType:文件类型(0:其他文件; 1:用户头像; 2:设备; 3:广告素材; 4：数据报告; 5:公司资料; 6:效果监播)
 */
function showUploadFile($imageUrlFile, $imageShowDiv, $imageUrlId, $fileType, isImg) {
	var fileObjs = document.getElementById($imageUrlFile);
	var fileList = fileObjs.files;
	for (var i = 0; i < fileList.length; i++) {
		if(isImg){
			if (!/\.(gif|jpg|jpeg|png|bmp)$/.test(fileList[i].name.toLowerCase())) {
				$("#" + $imageUrlFile).tips({
					side : 3,
					msg : '图片类型必须是gif、jpeg、jpg、png、bmp格式',
					bg : '#1abc9d',
					time : 5
				});
				return false;
			}
		}else{
			if (!/\.(pdf)$/.test(fileList[i].name.toLowerCase())) {
				$("#" + $imageUrlFile).tips({
					side : 3,
					msg : '请上传PDF格式文件',
					bg : '#1abc9d',
					time : 5
				});
				return false;
			}
		}
	}
	
	var url="";
	var html="";
	var imageShowDiv = document.getElementById($imageShowDiv);
	
	// 调用接口
	for (var i = 0; i < fileList.length; i++) {
		var formdata = new FormData();
		formdata.append("dataFile", fileList[i]);
		formdata.append("fileType", $fileType);
		$.ajax({
			type : 'POST',
			url : 'file/uploadFile',
			data : formdata,
			dataType : "json",
//			async : false,
			cache : false,
			contentType : false,// 必须false才会自动加上正确的Content-Type
			processData : false,// 必须false才会避开jQuery对formdata的默认处理,XMLHttpRequest会对 formdata进行正确的处理
			beforeSend : function() {
				//创建LoadingDiv
				createLoadingDiv();
			},
			success : function(response) {
				if (response.code == 0) {
					// showAlert("文件上传成功!");
					// 获取返回路径
					url += response.data.url+",";
					html += fillFileDiv(response.data.url);
					//html += "&nbsp;<a href='javascript:openUploadFileUrl(\""+response.data+"\");'>预览_"+fileList[i].name+"</a>&nbsp;&nbsp;";
				} else {
					showAlert(response.message);
				}
				if (url != "" && url.length > 0) {
					imageShowDiv.innerHTML = html;
					$("#" + $imageUrlId).val(url.substring(0, url.length - 1));
				}
			},
			error : function(data) {
				//关闭LoadingDiv
				closeLoadingDiv();
				showAlert(fileList[i]+"上传失败!");
			}, 
			complete : function() {
				//关闭LoadingDiv
				closeLoadingDiv();
			}
		});
	}
	return false;
}